import { Component, lazy } from 'react'
/* -------------------------------------------------------- Sync Component -- */
import PageLoading from '@tp/page-loading'
/* -------------------------------------------------------- Async Component -- */
const NotFound 	= lazy(()=>import('@views/404'))
/**
 * 异步加载路由组件
 * @param {Function}	imports 	# 引入组件 () => import()
 * @param {String}		path 				# 路径
 */
const Lazy = (imports, path) => {
	return class My extends Component {
		
		state = { Component: () => <PageLoading/> }
	
		async componentDidMount() {
			if( imports ){
				// imports().then(f => this.setState({ Component: f.default } ) )
				const { default: Component } = await imports()
				this.setState({ Component })
			}else{
				console.error(`组件不存在: ${path}.jsx`)
				this.setState({ Component: () => <NotFound isComponent path={`${path}.jsx`}/> })
			}
		}
		
		componentWillUnmount(){
			// this.setState = (state, callback) => { return }
			this.setState = () => false
			window.$http?.stop?.()
		}

		render() {
			const { Component } = this.state
			return Component ? <Component {...this.props} /> : <NotFound isComponent path={`${path}.jsx`} />
		}
	}
}

const modules = [
	import.meta.glob(`../../../../views/*`),
	import.meta.glob('../../../../views/*/*'),
	import.meta.glob('../../../../views/*/*/*'),
	import.meta.glob('../../../../views/*/*/*/*'),
	import.meta.glob('../../../../views/*/*/*/*/*'),
	import.meta.glob('../../../../../views/*/*/*/*/*')
]

const Index = path => {
	if(!path) return <NotFound isComponent />
	const index = path.split('/').length - 1
	let imports = modules[index][`../../../../views/${path}.jsx`]
	if( Boolean(imports) === false ) imports = modules[index + 1]?.[`../../../../views/${path}/index.jsx`]
	return Lazy(imports, path )
}

export default Index